package com.woniu.adopt_web.config;

import com.woniu.adopt_web.entity.UserLogLogin;
import com.woniu.adopt_web.mapper.UserLogLoginMapper;
import com.woniu.adopt_web.vo.UserVo;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 登录aop 用于记录登录记录
 */
@Aspect
@Component
public class LoginAspect {
    @Autowired
    UserLogLoginMapper userLogLoginMapper;

    @AfterReturning(value = "execution(* com.woniu.adopt_web.service.UserService.login(..))",returning = "obj")
    public void loginLog(Object obj){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
        if (obj!=null){
            // 创建日志对象
            UserLogLogin userLogLogin = new UserLogLogin();
            // 获取 IP 地址
            String addr = request.getRemoteAddr();

            UserVo userVo = (UserVo)obj;
            userLogLogin.setUserId(userVo.getId());
            userLogLogin.setLogintime(new Date());
            userLogLogin.setIpaddress(addr);
            // 把登录日志信息存到数据库
            userLogLoginMapper.insert(userLogLogin);
        }
    }
}
